package com.doubao.hardware.controller;

import com.doubao.hardware.config.IotMqConfig;
import com.doubao.hardware.dto.ApiResponse;
import com.doubao.hardware.service.MqttService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Map;

/**
 * MQTT控制器
 * 提供MQTT测试和消息发送接口
 */
@RestController
@RequestMapping("/api/mqtt")
@RequiredArgsConstructor
@Slf4j
public class MqttController {

    private final MqttService mqttService;
    private final IotMqConfig iotMqConfig;

    /**
     * 测试MQTT连接状态
     * @return 连接状态
     */
    @GetMapping("/status")
    public ApiResponse<Map<String, Object>> checkStatus() {
        boolean connected = mqttService.isConnected();

        Map<String, Object> result = new HashMap<>();
        result.put("connected", connected);
        result.put("broker", iotMqConfig.getServerURI());
        result.put("topic", iotMqConfig.getDefaultTopic());

        if (connected) {
            return ApiResponse.success("MQTT连接正常", result);
        } else {
            return ApiResponse.error(503, "MQTT未连接", result);
        }
    }

    /**
     * 重新连接MQTT
     * @return 连接结果
     */
    @PostMapping("/reconnect")
    public ApiResponse<Void> reconnect() {
        boolean success = mqttService.reconnect();

        if (success) {
            return ApiResponse.success("MQTT重连成功");
        } else {
            return ApiResponse.error("MQTT重连失败");
        }
    }

    /**
     * 发送消息
     * @param payload 消息内容
     * @return 发送结果
     */
    @PostMapping("/send")
    public ApiResponse<Void> sendMessage(@RequestBody Map<String, String> payload) {
        if (payload == null || !payload.containsKey("message")) {
            return ApiResponse.error("消息内容不能为空");
        }

        String message = payload.get("message");
        log.info("发送MQTT消息: {}", message);

        boolean success = mqttService.sendMessage(message);

        if (success) {
            return ApiResponse.success("消息发送成功");
        } else {
            return ApiResponse.error("消息发送失败");
        }
    }

    /**
     * 发送消息到指定主题
     * @param topic 主题
     * @param payload 消息内容
     * @return 发送结果
     */
    @PostMapping("/send/{topic}")
    public ApiResponse<Void> sendMessageToTopic(
            @PathVariable String topic,
            @RequestBody Map<String, String> payload) {

        if (payload == null || !payload.containsKey("message")) {
            return ApiResponse.error("消息内容不能为空");
        }

        String message = payload.get("message");
        log.info("发送MQTT消息到主题 {}: {}", topic, message);

        boolean success = mqttService.sendMessageToTopic(topic, message);

        if (success) {
            return ApiResponse.success("消息发送成功");
        } else {
            return ApiResponse.error("消息发送失败");
        }
    }
}